package com.party.jackclientandroid.ui_home.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.party.jackclientandroid.BaseActivityTitle;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.OrderService;
import com.party.jackclientandroid.api.ShopService;
import com.party.jackclientandroid.api.UserService;
import com.party.jackclientandroid.base.BaseTextWatch;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.CommonResult;
import com.party.jackclientandroid.bean.DiscountPayBillBean;
import com.party.jackclientandroid.bean.PayResult;
import com.party.jackclientandroid.controller.DialogController;
import com.party.jackclientandroid.controller.PayController;
import com.party.jackclientandroid.ui_mine.RecommendPresentActivity;
import com.party.jackclientandroid.utils.Utils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * 优惠买单
 */
public class DiscountPayBillActivity extends BaseActivityTitle {
    @BindView(R.id.xiacoin_text)
    TextView xiacoinText;
    @BindView(R.id.xiacoin_total)
    TextView xiacoinTotal;
    @BindView(R.id.xiacoin_money)
    TextView xiacoinMoney;
    @BindView(R.id.xiacoin_check)
    CheckBox xiacoinCheck;
    @BindView(R.id.xiacoin_ll)
    LinearLayout xiacoinLl;
    @BindView(R.id.total_money_y)
    TextView total_money_y;
    @BindView(R.id.total_money_et)
    EditText total_money_et;
    @BindView(R.id.not_add_y)
    TextView not_add_y;
    @BindView(R.id.not_add_et)
    EditText not_add_et;
    @BindView(R.id.discount_checkbox_ll)
    LinearLayout discount_checkbox_ll;
    @BindView(R.id.rebate_money_ll)
    LinearLayout rebate_money_ll;
    @BindView(R.id.not_discount_ll)
    LinearLayout not_discount_ll;
    @BindView(R.id.discount_price)
    TextView discount_price;
    @BindView(R.id.is_discount_check)
    CheckBox is_discount_check;
    @BindView(R.id.is_rebate_check)
    CheckBox is_rebate_check;
    @BindView(R.id.real_price_tv)
    TextView real_price_tv;
    @BindView(R.id.discount_tv)
    TextView discount_tv;//折扣显示
    @BindView(R.id.rebate_money_total)
    TextView rebate_money_total;
    @BindView(R.id.rebate_money)
    TextView rebate_money;
    @BindView(R.id.pay_btn)
    Button pay_btn;

    private String shopId;
    private String xiaPinCoin;
    private ShopService shopService;
    private UserService userService;
    private DiscountPayBillBean disCoupon;
    private String isUseXiapinCoin = "0";
    private String payMoneyStr;
    private long unsealingTime;
    private String remarks;
    private String notDisMoney = "0";
    private String useRebateMoney = "0";//使用了多少优惠金

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discount_pay_bill);
        ButterKnife.bind(this);
        getIntentData(getIntent());
        getNeedData();
        requestData();
    }

    private void getIntentData(Intent intent) {
        shopId = intent.getStringExtra("shopId");
    }

    public interface PayCompleteListener {
        void payOk(BaseResult<PayResult> result);

        void payFail(String errorMessage);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
        initLister();
    }


    private void initLister() {
        requestEdit(total_money_y, total_money_et);
        requestEdit(not_add_y, not_add_et);

        is_discount_check.setOnCheckedChangeListener((CompoundButton buttonView, boolean isChecked) -> {
            not_discount_ll.setVisibility(isChecked ? View.VISIBLE : View.GONE);
            refreshPayMoney();
        });

        total_money_et.addTextChangedListener(new BaseTextWatch() {
            @Override
            public void afterTextChanged(Editable s) {
                if (!checkNumber(s)) return;
                refreshPayMoney();
            }
        });

        is_rebate_check.setOnCheckedChangeListener((CompoundButton buttonView, boolean isChecked) -> {
            refreshPayMoney();
        });


        xiacoinCheck.setOnCheckedChangeListener((CompoundButton buttonView, boolean isChecked) -> {
            refreshPayMoney();
        });

        not_add_et.addTextChangedListener(new BaseTextWatch() {
            @Override
            public void afterTextChanged(Editable s) {
                if (!checkNumber(s)) return;
                refreshPayMoney();
            }
        });
    }

    private void requestData() {
        addDisposableIoMain(userService.getUserWallet(), new DefaultConsumer<CommonResult>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<CommonResult> baseBean) {
                unsealingTime = baseBean.getData().getUnsealingTime();
                remarks = baseBean.getData().getRemarks() + "";
                if (unsealingTime != 0) {
                    DialogController.showMonitoringDialog(DiscountPayBillActivity.this, remarks, unsealingTime);
                }
            }
        });
    }

    private void refreshPayMoney() {
        try {
            orderId = null;
            //输入的总额
            BigDecimal totalBd = new BigDecimal("0");
            //不参与打折的金额
            BigDecimal notDisBd = new BigDecimal("0");

            //需要被打折的钱
            BigDecimal needDisMoney = null;
            // 实付金额
            BigDecimal payMoneyBg;

            //用户可使用的消费金  0.6    1000 * 0.6 = 600
            String total_money = total_money_et.getText().toString();
            notDisMoney = not_add_et.getText().toString();
            if (notDisMoney.trim().length() == 0) notDisMoney = "0";

            if (total_money != null && total_money.trim().length() > 0) {
                totalBd = new BigDecimal(total_money);
            }

            //选择不参与优惠
            if (is_discount_check.isChecked()) {
                notDisBd = new BigDecimal(notDisMoney);

                if (notDisBd.floatValue() > totalBd.floatValue()) {
                    not_add_et.setText(total_money_et.getText().toString());
                    not_add_et.setSelection(not_add_et.getText().toString().length());
                    return;
                }
            }

            //计算需要打折的金额
            needDisMoney = calDiscount(totalBd, notDisBd);


            //计算返利金
            payMoneyBg = calRebate(needDisMoney, notDisBd);

            //计算消费金
            payMoneyBg = calXiaPinCoin(payMoneyBg, needDisMoney.add(notDisBd));

            payMoneyStr = payMoneyBg.setScale(2, BigDecimal.ROUND_HALF_DOWN).toString();
            real_price_tv.setText(payMoneyStr);
            pay_btn.setText(payMoneyStr + "元 确认买单");

        } catch (Exception e) {
            System.out.println(e);
            DialogController.showConfirmDialog(mActivity, "", e.getMessage());
        }
    }

    private BigDecimal calXiaPinCoin(BigDecimal payMoneyBg, BigDecimal needDisMoney) {
        if (!xiacoinCheck.isChecked()) return payMoneyBg;

        BigDecimal xiapinBg = new BigDecimal(xiaPinCoin);//自己账户有多少消费金
        BigDecimal maxCoinBg = new BigDecimal(disCoupon.getMaxUseXiapinMoney());//最多使用多少消费金
        BigDecimal xiaPinLimit = needDisMoney.multiply(new BigDecimal(disCoupon.getXiapinUseDiscount()));

        //如果 最大值 < 瞎拼限制， 取小的作为限制。
        if (maxCoinBg.floatValue() < xiaPinLimit.floatValue()) xiaPinLimit = maxCoinBg;

        //如果消费金大于可使用的消费金
        if (xiapinBg.floatValue() > xiaPinLimit.floatValue()) xiapinBg = xiaPinLimit;

        //如果付款金额 >= 消费经 那么 就需要减去 付款金额，算出还剩下多少消费经。
        if (payMoneyBg.floatValue() >= xiapinBg.floatValue()) {
            payMoneyBg = payMoneyBg.subtract(xiapinBg);
            isUseXiapinCoin = xiapinBg.setScale(2, BigDecimal.ROUND_HALF_DOWN).toString();
            xiacoinMoney.setText("- ¥" + isUseXiapinCoin);
        } else {//如果 付款金额 < 消费经
            isUseXiapinCoin = payMoneyBg.setScale(2, BigDecimal.ROUND_HALF_DOWN).toString();
            xiacoinMoney.setText("- ¥" + isUseXiapinCoin);
            payMoneyBg = new BigDecimal("0");
        }
        return payMoneyBg;
    }

    private BigDecimal calRebate(BigDecimal needDisMoney, BigDecimal notDisBd) {
        BigDecimal disMoney;
        if (is_rebate_check.isChecked()) {
            BigDecimal rebateBd = new BigDecimal(disCoupon.getShopRebateMoney()); //返利金
            disMoney = needDisMoney.subtract(rebateBd);
            if (disMoney.floatValue() < 0) {
                disMoney = new BigDecimal("0");
                useRebateMoney = needDisMoney.toString();
            } else {
                useRebateMoney = rebateBd.toString();
            }
            rebate_money.setText("- ¥ " + useRebateMoney);
        } else {
            rebate_money.setText("- ¥ 0");
            disMoney = needDisMoney;
        }
        return disMoney.add(notDisBd);
    }

    //计算需要打折的金额
    private BigDecimal calDiscount(BigDecimal totalBd, BigDecimal notDisBd) {
        BigDecimal needDisMoney = totalBd.subtract(notDisBd);
        if (disCoupon.getIsUseDiscount() == 1) {//当前是首单
            //需要打折的金额 * 折扣 + 不打折的价格 = 最终价格。
            BigDecimal discountBg = new BigDecimal(disCoupon.getDiscount());//折扣
            if (discountBg.floatValue() < 1) {
                BigDecimal disMoney = needDisMoney.multiply(new BigDecimal("1").subtract(discountBg));//折扣后的金额
                discount_price.setText("-" + disMoney.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                needDisMoney = needDisMoney.subtract(disMoney);
            }
        }
        return needDisMoney;
    }

    private void showKeyboard(EditText et) {
        et.setFocusable(true);
        et.setFocusableInTouchMode(true);
        et.requestFocus();
        et.setSelection(et.getText().toString().length());
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(et, 0);
    }

    public void getNeedData() {
        shopService = new ShopService(this);
        userService = new UserService(this);
        addDisposableIoMain(shopService.getDiscountPayBill(shopId), new DefaultConsumer<DiscountPayBillBean>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<DiscountPayBillBean> baseBean) {
                disCoupon = baseBean.getData();
                xiacoinLl.setVisibility(View.VISIBLE);
                if (disCoupon.getIsUseXiapinCoin() == 0) {
                    xiacoinLl.setVisibility(View.GONE);
                    isUseXiapinCoin = "0";
                }
                if (disCoupon.getIsUseDiscount() == 1) {
                    float v = Float.parseFloat(disCoupon.getDiscount());
                    if (v < 1f) {
                        discount_checkbox_ll.setVisibility(View.VISIBLE);
                        discount_tv.setText("首单" + Utils.changeStr10(disCoupon.getDiscount()) + "折");
                    }
                }
                rebate_money_ll.setVisibility(View.VISIBLE);
                rebate_money_total.setText("(¥ " + disCoupon.getShopRebateMoney() + ")");
                setMiddleText(disCoupon.getShopName());
            }
        });
    }

    private void requestEdit(View view, EditText et) {
        view.setOnClickListener((View v) -> {
            showKeyboard(et);
        });
    }


    private void initData() {
        walletController = new PayController(mActivity, pay_btn);
        if (disCoupon == null) {
            shopService = new ShopService(this);
            addDisposableIoMain(shopService.getDiscountPayBill(shopId), new DefaultConsumer<DiscountPayBillBean>(mApplication) {
                @Override
                public void operateSuccess(BaseResult<DiscountPayBillBean> baseBean) {
                    walletController.preloading((CommonResult bean) -> {
                        xiaPinCoin = bean.getXiapinCoin();
                        xiacoinTotal.setText("(¥" + xiaPinCoin + ")");
                    });

                    disCoupon = baseBean.getData();
                    setMiddleText(disCoupon.getShopName());
                }
            });
        }
    }

    PayController walletController;
    private String orderId, rebateMoney;

    public void startPay(View v) {
        String total_money = total_money_et.getText().toString();
        String not_add_dis = not_add_et.getText().toString();

        walletController.showPayMethod(payMoneyStr, orderId, (View vv) -> {
            Map<String, String> data = new HashMap<>();
            data.put("token", mApplication.getToken());
            data.put("totalPrice", total_money);
            data.put("finalPrice", payMoneyStr);
            data.put("shopId", shopId + "");
            data.put("useRebateMoney", useRebateMoney);
            data.put("isDiscount", disCoupon.getIsUseDiscount() + "");
            data.put("noDiscountPrice", is_discount_check.isChecked() ? not_add_dis : "0");
            data.put("useXiapinCoin", isUseXiapinCoin);
            data.put("couponNum", "0");
            data.put("couponId", "0");
            data.put("userPhone", mApplication.getUser().getPhone());
            OrderService orderService = new OrderService(mActivity);
            addDisposableIoMain(orderService.addDiscountOrder(data), new DefaultConsumer<CommonResult>(mApplication) {
                @Override
                public void operateSuccess(BaseResult<CommonResult> result) {
                    orderId = result.getData().getId() + "";
                    rebateMoney = result.getData().getRebateMoney();
                    walletController.pay(orderId);
                }
            });
        });

        walletController.setInputPassFinish(new PayCompleteListener() {
            @Override
            public void payOk(BaseResult<PayResult> result) {
                Intent intent = new Intent(getApplicationContext(), PaymentSuccessActivity.class);
                intent.putExtra("shopName", disCoupon.getShopName());
                intent.putExtra("totalMoney", total_money);
                intent.putExtra("notDisMoney", notDisMoney);
                intent.putExtra("rebateMoney", rebateMoney);
                intent.putExtra("useRebateMoney", useRebateMoney);
                intent.putExtra("isUseXiapinCoin", isUseXiapinCoin);
                intent.putExtra("payMoney", payMoneyStr);
                startActivity(intent);
                finish();
            }

            @Override
            public void payFail(String errorMessage) {
                System.out.println(errorMessage);
            }
        });
    }
}
